package cn.edu.sjtu.user_management.controller;

import cn.edu.sjtu.user_management.dto.UpdateRoleForm;
import cn.edu.sjtu.user_management.dto.UserDTO;
import cn.edu.sjtu.user_management.exception.model.ServiceException;
import cn.edu.sjtu.user_management.model.RespStatus;
import cn.edu.sjtu.user_management.model.Result;
import cn.edu.sjtu.user_management.model.User;
import cn.edu.sjtu.user_management.service.UserService;
import cn.edu.sjtu.user_management.util.ResultUtil;
import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;


@RestController
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private Mapper mapper;

    @RequestMapping(value = "/user", method = RequestMethod.POST)
    public Result signUp(@Valid @RequestBody User user, BindingResult result) {
        if (result.hasErrors()) {
            throw new ServiceException(RespStatus.WRONG_INFORMATION, result.getFieldError().getDefaultMessage());
        }
        userService.signUp(user);
        return ResultUtil.success();
    }

    @RequestMapping(value = "/user", method = RequestMethod.PUT)
    public Result updateUserRole(@Valid @RequestBody UpdateRoleForm updateRoleForm, BindingResult result) {
        if (result.hasErrors()) {
            throw new ServiceException(RespStatus.WRONG_INFORMATION, result.getFieldError().getDefaultMessage());
        }
        User user = userService.updateUserRole(updateRoleForm.getUserId(), updateRoleForm.getNewRole());
        UserDTO userDTO = mapper.map(user, UserDTO.class);
        return ResultUtil.success(userDTO);
    }

    @RequestMapping(value = "/user", method = RequestMethod.GET)
    public Result findUser(String username, String userId, String password, Integer role) {
        List<User> users = userService.findUser(username, userId, password, role);
        List<UserDTO> userDTOs = users.stream().map(user -> mapper.map(user, UserDTO.class)).collect(Collectors.toList());
        return ResultUtil.success(userDTOs);
    }

}
